package com.wushijia.highconcurrency.future;

import com.wushijia.sql.DbUtil;
import java.sql.Connection;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;

public class FutureTest2 {

  public static void main(String[] args) {
    try {
      //如果使用超时方法，会抛出超时错误而屏蔽真实错误
      double price = getPrice1().get();
      System.out.println(price);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  //用于提示错误的异常会被限制在试图计算商品价格的当前线程的范围内，最终会杀死该线程，而这会导致等待get方法返回结果的客户端永久地被阻塞
  private static Future<Double> getPrice1() {
    CompletableFuture<Double> futurePrice = new CompletableFuture<>();
    new Thread(() -> {
      double price = calculatePrice();
      futurePrice.complete(price);
    }).start();
    return futurePrice;
  }

  //使用CompletableFuture的completeExceptionally方法将导致CompletableFuture内发生问题的异常抛出
  private static Future<Double> getPrice2() {
    CompletableFuture<Double> futurePrice = new CompletableFuture<>();
    new Thread(() -> {
      try {
        double price = calculatePrice();
        futurePrice.complete(price);
      } catch (Exception e) {
        futurePrice.completeExceptionally(e);
      }
    }).start();
    return futurePrice;
  }

  //等价于getPrice2()
  private static Future<Double> getPrice3() {
    return CompletableFuture.supplyAsync(FutureTest2::calculatePrice);
  }

  private static double calculatePrice() {

    Connection connection = DbUtil.getConnection();

//    throw new RuntimeException("计算价格时报错");

    return new Random().nextDouble();
  }

}
